#include "sysinitdb.h"
#include "userconfigs.h"
#include "server_global.h"
#include "dbqueriesthread.h"
#include "commonfunc.h"

SysInitDb::SysInitDb()
{

}

DbQueryBaseThreadPtr SysInitDb::newQueriesThread(CnsComponentPtr com, QVariantHash& sv)
{
    DbQueriesThreadPtr pt = FRAMEWORK->getComponent("/server/.//dbQueriesThread").staticCast<DbQueriesThread>();
    pt->execInNs("initDbQueriesThread", "",
               Q_ARG(QVariantHash&, sv), Q_ARG(QScopedPointer<QThread>&, pt->getWorkThread()));
    connect(pt.data(), &DbQueryBaseThread::dbQueryThreadFinished, this, [com](CnsComponentPtr tcom){
        DbQueryBaseThread* thread = static_cast<DbQueryBaseThread*>(tcom.data());
        if(thread->isForceStop())return;

        UserConfigsPtr userConfigsPtr = com->property("userConfigs").value<UserConfigsPtr>();
        userConfigsPtr->setValue("db", "initDb", "true");
    });

    return pt;
}

void SysInitDb::f_start(CnsComponentPtr com)
{
    UserConfigsPtr userConfigsPtr = com->property("userConfigs").value<UserConfigsPtr>();
    userConfigsPtr->settings_init();
    const QString &initDb = userConfigsPtr->getValue("db", "initDb");
    if(initDb!="true"){
        QVariantHash sv;
        sv["fileName"] = com->property("fileName");
        DbQueryBaseThreadPtr p = newQueriesThread(com, sv);
        com->setProperty(QVariant::fromValue(p), "thread");
    }
}

void SysInitDb::run_b(CnsComponentPtr com, uv_loop_t *loop)
{
    DbQueryBaseThreadPtr p = com->property("thread").value<DbQueryBaseThreadPtr>();
    if(p.data()){
        p->getWorkThread()->wait();
        int ret = FRAMEWORK->removeRefObj(p->getObjFullPath(), true);
        assert(ret);
    }
}
